package org.example.servlet;

import org.example.dao.CartDAO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import org.json.JSONObject;

@WebServlet("/cart/*")
public class CartServlet extends HttpServlet {
    private CartDAO cartDAO = new CartDAO();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        // 设置请求编码
        request.setCharacterEncoding("UTF-8");
        // 设置响应类型
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        JSONObject result = new JSONObject();
        
        try {
            String pathInfo = request.getPathInfo();
            Integer userId = (Integer) request.getSession().getAttribute("userId");
            
            if (userId == null) {
                result.put("success", false);
                result.put("message", "请先登录");
                out.print(result.toString());
                return;
            }

            if ("/update".equals(pathInfo)) {
                // 更新购物车数量
                String cartIdStr = request.getParameter("cartId");
                String quantityStr = request.getParameter("quantity");
                
                if (cartIdStr == null || cartIdStr.trim().isEmpty() || 
                    quantityStr == null || quantityStr.trim().isEmpty()) {
                    result.put("success", false);
                    result.put("message", "参数错误");
                    out.print(result.toString());
                    return;
                }
                
                Integer cartId = Integer.parseInt(cartIdStr.trim());
                Integer quantity = Integer.parseInt(quantityStr.trim());
                
                if (quantity < 1) {
                    result.put("success", false);
                    result.put("message", "数量必须大于0");
                    out.print(result.toString());
                    return;
                }
                
                boolean success = cartDAO.updateQuantity(cartId, quantity);
                result.put("success", success);
                
            } else if ("/remove".equals(pathInfo)) {
                // 删除购物车商品
                String cartIdStr = request.getParameter("cartId");
                
                if (cartIdStr == null || cartIdStr.trim().isEmpty()) {
                    result.put("success", false);
                    result.put("message", "购物车ID不能为空");
                    out.print(result.toString());
                    return;
                }
                
                try {
                    Integer cartId = Integer.parseInt(cartIdStr.trim());
                    boolean success = cartDAO.removeFromCart(cartId);
                    result.put("success", success);
                    if (!success) {
                        result.put("message", "删除失败，请重试");
                    }
                } catch (NumberFormatException e) {
                    result.put("success", false);
                    result.put("message", "无效的购物车ID");
                }
                
            } else if ("/add".equals(pathInfo)) {
                // 添加商品到购物车
                Integer productId = Integer.parseInt(request.getParameter("productId"));
                Integer quantity = Integer.parseInt(request.getParameter("quantity"));
                boolean success = cartDAO.addToCart(userId, productId, quantity);
                result.put("success", success);
                if (!success) {
                    result.put("message", "添加购物车失败");
                }
            }
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        
        out.print(result.toString());
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 重定向到购物车页面
        response.sendRedirect(request.getContextPath() + "/cart.jsp");
    }
} 